<template>
  <div>
    <van-nav-bar
      title="登录"
      left-text="返回"
      right-text="..."
      left-arrow
      @click-left="$router.go(-1)" 
    />
    <div class="login">
      <van-form @submit="login">
        <van-field
          v-model="formData.phone"
          name="用户名"
          placeholder="用户名"
          :rules="[
            {
              required: true,
              pattern: /^1[3-9]\d{9}$/,
              message: '请填写用户名',
            },
          ]"
        />
        <van-field
          v-model="formData.pass"
          type="password"
          name="密码"
          placeholder="密码"
          :rules="[
            { required: true, pattern: /^\d{4}$/, message: '请填写密码' },
          ]"
        />
        <div style="margin: 16px">
          <van-button round block type="info" native-type="submit"
            >登录</van-button
          >
        </div>
      </van-form>
      <div class="register" @click="toRegister">注册</div>
    </div>
  </div>
</template>

<script>
// 导入封装好的axios
import { user_login } from "../utils/api";
export default {
  data() {
    return {
      formData: {
        phone: "",
        pass: "",
      },
    };
  },
  methods: {
    login() {
      // 发起登录请求
      user_login(this.formData).then((res) => {
        if (res.data.code == 200) {
          // 保存用户信息，token
          localStorage.setItem("token", res.data.token);
          localStorage.setItem("userinfo", JSON.stringify(res.data.userinfo));
          // 自动跳转到首页
          this.$router.push("/");
        } else {
          alert("登录失败");
        }
      });
    },
    toRegister() {
      this.$router.push("/register");
    },
  },
};
</script>

<style lang="scss" scoped>
.login {
  margin: 50% 20px;
  //   background-color: aqua;
  .register {
    width: 90%;
    height: 40px;
    border-radius: 20px;
    margin: 16px;
    text-align: center;
    line-height: 40px;
    font-size: 15px;
    background-color: #ccc;
  }
}
.van-field {
  border: 1px solid gainsboro;
  border-radius: 20px;
  margin: 20px 0;
}
.login .title {
  font-weight: bold;
  text-align: center;
  line-height: 40px;
}

.login .input-box {
  height: 40px;
  border: 1px solid #ccc;
  border-radius: 20px;
  padding-left: 20px;
  box-sizing: border-box;
  outline: none;
  width: 100%;
  margin: 20px 0;
}
</style>
